<script setup lang="ts">
    import { reqGetSuggestion } from "@/api/search";
    import router from "@/router";
    import { getHistroyList, setHistroyList } from "@/utils/storage";
    import { Toast } from "vant";
    import { computed, ref } from "vue";

    const keywords = ref("");
    const sugList = ref<string[]>([]);
    const historyList = ref<string[]>(getHistroyList() || []);
    // 节流时间
    const timeId = ref<NodeJS.Timeout>();
    // 语法高亮
    const showSugList = computed(() => {
        // 先判断sugList列表里有没有值，不然别做筛选显示
        let arr: string[] = [];
        if (sugList.value[0]) {
            // 创建正则规则，拿当前输入框里面的值进行筛选高亮，gi是全局跟不分大小写的意思
            const regExp = new RegExp(keywords.value, "gi");
            // 返回一个处理过的数组，这个数组里放处理好的html结构实现高亮
            arr = sugList.value.map((item) => {
                // 使用正则校验，替换掉原文本中需要高亮的部分并返回
                return item.replace(regExp, (value: string) => {
                    // 因为要把原来的值放入span标签里实现高亮，所以这里用函数返回值的方式传参回去
                    return `<span style="color: red;">${value}</span>`;
                });
            });
        }
        return arr;
    });
    // 搜索
    const onSearch = (keywords: string) => {
        if (keywords === "") return Toast.fail("没有值");
        if (historyList.value.findIndex((item) => item === keywords) === -1) {
            historyList.value.unshift(keywords);
            setHistroyList(historyList.value);
        }
        router.push({ path: "/searchResult", query: { keywords } });
    };
    // 得到搜索建议
    const getSuggestion = () => {
        clearTimeout(timeId.value as NodeJS.Timeout);
        timeId.value = setTimeout(async () => {
            if (keywords.value === "") return;
            const {
                data: { data },
            } = await reqGetSuggestion(keywords.value);
            sugList.value = data.options;
        }, 300);
    };
    // 联想建议搜索
    const sugSearch = (index: number) => {
        onSearch(sugList.value[index]);
    };
    // 删除搜索历史
    const delHistory = (index: number) => {
        historyList.value = historyList.value.filter((item, i) => i !== index);
        setHistroyList(historyList.value);
    };
</script>
<template>
    <div class="search-container">
        <router-view></router-view>
        <van-nav-bar
            title="搜索中心"
            left-text="返回"
            left-arrow
            @click-left="$router.push('/home')" />
        <van-search
            show-action
            placeholder="请输入搜索关键词"
            shape="round"
            v-model.trim="keywords"
            @input="getSuggestion"
            @search="onSearch(keywords)">
            <template #action>
                <div @click="onSearch(keywords)">搜索</div>
            </template>
        </van-search>
        <!-- 联想建议 -->
        <van-cell-group v-if="keywords">
            <van-cell
                v-for="(item, index) in showSugList"
                :key="index"
                @click="sugSearch(index)"
                icon="search">
                <div v-html="item"></div>
            </van-cell>
        </van-cell-group>
        <!-- /联想建议 -->

        <!-- 搜索历史记录 -->
        <van-cell-group v-else>
            <van-cell title="历史记录"> </van-cell>
            <van-cell
                @click="onSearch(item)"
                v-for="(item, index) in historyList"
                :key="index"
                :title="item">
                <!-- 这里他妈的有个冒泡行为 -->
                <van-icon
                    class="close"
                    @click.stop="delHistory(index)"
                    name="close" />
            </van-cell>
        </van-cell-group>
        <!-- /搜索历史记录 -->
    </div>
</template>

<style lang="scss" scoped>
    .close {
        font-size: 20px;
    }
</style>
